package com.red.servlet.user;

import com.red.entity.User;
import com.red.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

public class UserAddServlet extends HttpServlet {
    final static String NAME_PATTERN = "^.{2,16}$";
    final static String ACCOUNT_PATTERN = "^\\w{6,12}$";
    final static String PWD_PATTERN = "^[\\w_-]{6,16}$";
    final static String EMAIL_PATTERN = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String name = req.getParameter("uName");
        String account = req.getParameter("uAccount");
        String password = req.getParameter("uPassword");
        String email = req.getParameter("uEmail");
        int level = Integer.parseInt(req.getParameter("uLevel"));

        String info = "";

        if (!Pattern.matches(NAME_PATTERN, name)) info="用户名格式不正确";
        else if (!Pattern.matches(ACCOUNT_PATTERN, account)) info="账号格式不正确";
        else if (!Pattern.matches(PWD_PATTERN, password)) info="密码格式不正确";
        else if (!Pattern.matches(EMAIL_PATTERN, email)) info="邮箱格式不正确";
        else if (level < 0 || level > 3) info = "用户等级溢出";
        else {
            User user = new User(name, account, password, email, level);
            if (new UserServiceImpl().add(user))info = "添加成功";
            else info = "用户已存在";
        }
        req.setAttribute("addResult", info);
        req.getRequestDispatcher("user_manage").forward(req, resp);
    }
}
